import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:rangers_applog_flutter_plugin/rangers_applog_flutter_plugin.dart';

void main() {
  // 关键：确保 binding 已初始化，否则会抛 Null check
  TestWidgetsFlutterBinding.ensureInitialized();

  const MethodChannel channel = MethodChannel('rangers_applog_flutter_plugin');
  // 记录最近一次调用参数，方便断言
  MethodCall? lastCall;
  dynamic lastResult;

  setUp(() {
    // 使用新的 API 打桩
    TestDefaultBinaryMessengerBinding.instance?.defaultBinaryMessenger
        .setMockMethodCallHandler(channel, (MethodCall methodCall) async {
      lastCall = methodCall;
      switch (lastCall?.method) {
        case 'getDeviceId':
          return 'mock-device-id-007';
        case 'setHeaderInfo':
        case 'setUserUniqueId':
          return null; // 无返回值
        default:
          return '42'; // 兜底
      }
    });
  });

  tearDown(() {
    TestDefaultBinaryMessengerBinding.instance?.defaultBinaryMessenger
        .setMockMethodCallHandler(channel, null);
    lastCall = null;
  });

  testWidgets('setHeaderInfo sends correct map', (WidgetTester tester) async {
    final header = {'header_key': 'header_value'};
    RangersApplogFlutterPlugin.setHeaderInfo(header);

    expect(lastCall?.method, 'setHeaderInfo');
    expect(lastCall?.arguments, {'customHeader': header});
  });

  testWidgets('getDeviceId returns mocked device id',
      (WidgetTester tester) async {
    // 重新打桩：让 getDeviceId 返回固定的 mock 值
    TestDefaultBinaryMessengerBinding.instance?.defaultBinaryMessenger
        .setMockMethodCallHandler(channel, (MethodCall call) async {
      if (call.method == 'getDeviceId') {
        return 'mock-device-id-007';
      }
      return null;
    });

    // 执行异步调用
    final deviceId = await RangersApplogFlutterPlugin.getDeviceId();

    // 断言
    expect(deviceId, 'mock-device-id-007');
  });
  testWidgets('setUserUniqueId sends correct user id',
      (WidgetTester tester) async {
    const userId = 'user_9527';

    // 调用插件登录
    RangersApplogFlutterPlugin.setUserUniqueId(userId);

    // 断言插件通过 channel 发送了预期内容
    expect(lastCall?.method, 'setUserUniqueId');
    expect(lastCall?.arguments, {'uuid': userId});

    // 测试登出（传 null）
    RangersApplogFlutterPlugin.setUserUniqueId(null);
    expect(lastCall?.method, 'setUserUniqueId');
    expect(lastCall?.arguments, {'uuid': null});
  });
}
